<?php

namespace App\Kuafu\CouponExt\Model;

use App\Kuafu\Base\Model\Traits\KfUid;
use App\Kuafu\CouponExt\Enum\CouponExtCodeEnum;
use App\Kuafu\CouponExt\Enum\CouponExtEnum;
use App\Kuafu\CouponExt\Exceptions\CouponExtException;
use App\Kuafu\Order\Service\OrderDb;
use App\Kuafu\Order\Service\OrderService;
use App\Kuafu\Order\Service\OrderTable;
use App\Kuafu\User\Service\AuthService;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use App\Kuafu\Base\Model\BaseModel;
use Illuminate\Support\Facades\Log;

class OrderCouponExtSplitModel extends BaseModel
{
    use HasFactory, KfUid;

    protected $fillable = [
        'id',
        'brandId',
        'shopId',
        'orderId',
        'extPlatform',
        'couponExtSid',
        'couponExtCode',
        'couponExtName',
        'couponExtType',
        'couponExtCostPrice',
        'couponExtDue',
        'couponExtFee',
        'couponExtDiscountPrice',
        'couponExtStatus',
        'isDeleted',
        'createdByUid',
        'updatedByUid',
        'fee',
        'due'
    ];

    public static string $tableName;
    public static string $connectionName;

    public static function suffix($shopId)
    {
        if (is_int($shopId) && $shopId < 0) {
            $shopId = 0;
        }

        self::$tableName      = OrderTable::orderCouponExtTableName($shopId);
        self::$connectionName = OrderDb::orderDbConnection($shopId);

        return new static;
    }

    public function getTable()
    {
        return self::$tableName ?? parent::getTable();
    }

    public function getConnectionName()
    {
        return self::$connectionName ?? parent::getConnectionName();
    }

    /**
     * 新增核销券记录
     * @param int $shopId
     * @param int $orderId
     * @param int $extPlatform
     * @param string $couponSid
     * @param string $couponCode
     * @param string $couponTitle
     * @param int $couponType
     * @param int $userPay
     * @param int $deduction
     * @param int $num
     * @param int $couponStatus
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model
     * @throws CouponExtException
     */
    public static function addData(
        int $shopId,
        int $orderId,
        int $extPlatform,
        string $couponExtSid,
        string $couponExtCode,
        string $couponExtName,
        int $couponExtType,
        int $couponExtCostPrice,
        int $couponExtDiscountPrice,
        int $num,
        int $couponExtStatus
    ) {
        try {
            return self::query()->create(compact('shopId', 'orderId', 'extPlatform', 'couponExtSid', 'couponExtCode',
                'couponExtName', 'couponExtType', 'couponExtCostPrice', 'couponExtDiscountPrice', 'num',
                'couponExtStatus'));
        } catch (\Exception $e) {
            throw new CouponExtException(CouponExtCodeEnum::ERR_DB_ADD, '', $e);
        }
    }


    public static function batchAddData(array $data)
    {
        return self::query()->insert($data);
    }

    /**
     * 撤销券
     * @param int $orderId
     * @param string $couponCode
     * @return int
     */
    public static function cancelCoupon(int $orderId, string $couponCode)
    {
        try {
            $operateUid = AuthService::getUserId();
        } catch (\Exception $e) {
            $operateUid = 0;
        }

        return self::query()
                   ->where('orderId', $orderId)
                   ->where('couponExtCode', $couponCode)
                   ->where('couponExtStatus', CouponExtEnum::COUPON_STATUS_USED)
                   ->limit(1)
                   ->update([
                       'couponExtStatus' => CouponExtEnum::COUPON_STATUS_CANCEL,
                       'updatedByUid'    => $operateUid,
                   ]);
    }

    /**
     * 查询orderId下的所有用券记录
     * @param int $orderId
     * @param int $couponStatus
     * @param string $couponCode
     * @return \Illuminate\Support\Collection
     */
    public static function getCouponsByOrderId(
        int $orderId,
        int $couponStatus = CouponExtEnum::COUPON_STATUS_USED,
        string $couponCode = '',
        array $field = ['shopId', 'couponExtCode', 'extPlatform', 'couponExtCodeData']
    ) {
        return self::query()
                   ->where('orderId', $orderId)
                   ->when($couponCode, function ($q) use ($couponCode) {
                       $q->where('couponExtCode', $couponCode);
                   })
                   ->where('couponExtStatus', $couponStatus)
                   ->select($field)
                   ->get();
    }

    public static function getListByOrderIds($orderIds, $field)
    {
        return self::query()
                   ->whereIn('orderId', $orderIds)
                   ->select($field)
                   ->get();
    }

    /**
     * 更新订单的三方优惠券信息
     *
     * @param array $data
     */
    public static function updateOrderExtCoupon(string $orderId, array $data)
    {
        if (empty($data)) {
            return;
        }

        Log::channel('order')->debug('order_updateOrderExtCoupon_update', [
            '$orderId' => $orderId,
            '$data'    => $data,
        ]);


        foreach ($data as $key => $row) {
            if (empty($key)) {
                continue;
            }

            self::query()->where('id', $key)->update($row);
        }
    }
}
